package com.example.weight.wormHandle.garbageDisposal.onsiteDispose;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class WormIncoming extends AppCompatActivity {
    private String name, factory;
    private TitleBar titleBar;
    //来料日期
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    Date incomingDate = new Date(System.currentTimeMillis());
    private TextView worm_incoming_incomeDate;
    //来料重
    private EditText worm_income_weight;
    //桶重
    private EditText worm_bucket_weight;
    //水重
    private EditText worm_water_weight;
    //杂质重
    private EditText worm_impurity_weight;
    //来料净重
    private EditText worm_income_netweight;
    //进料重
    private EditText worm_feed_weight;
    //培育重
    private EditText worm_cultivation_weight;
    //丢弃重
    private EditText worm_throw_weight;
    //备注
    private EditText remark;
    String activeButton = new String();
    private TextWatcher weightChange_watcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.worm_incoming);
        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {WormIncoming.this.finish();}
            @Override
            public void onTitleClick(View v) {}
            @Override
            public void onRightClick(View v) {}
        });

        /**
         * 显示设置日期
         */
        worm_incoming_incomeDate = findViewById(R.id.worm_incoming_incomeDate);
        worm_incoming_incomeDate.setText(simpleDateFormat.format(incomingDate));
        /**
         *8个重量
         */
        //来料重
        worm_income_weight = findViewById(R.id.worm_income_weight);
        //桶重
        worm_bucket_weight = findViewById(R.id.worm_bucket_weight);
        //来料净重
        worm_income_netweight = findViewById(R.id.worm_income_netweight);
        //水重
        worm_water_weight = findViewById(R.id.worm_water_weight);
        //杂质重
        worm_impurity_weight = findViewById(R.id.worm_impurity_weight);
        //进料重
        worm_feed_weight = findViewById(R.id.worm_feed_weight);
        //培育重
        worm_cultivation_weight = findViewById(R.id.worm_cultivation_weight);
        //丢弃重
        worm_throw_weight = findViewById(R.id.worm_throw_weight);
        remark = findViewById(R.id.worm_incoming_remark);
        weightChange_watcher = new TextWatcher()  {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //这个方法被调用，说明在s字符串中，从start位置开始的count个字符即将被长度为after的新文本所取代。在这个方法里面改变s，会报错。
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //这个方法被调用，说明在s字符串中，从start位置开始的count个字符刚刚取代了长度为before的旧文本。在这个方法里面改变s，会报错。
            }
            @Override
            public void afterTextChanged(Editable s) {
                //这个方法被调用，那么说明s字符串的某个地方已经被改变。
                String income_weight = worm_income_weight.getText().toString().equals("")? "0.0" : worm_income_weight.getText().toString();
                String bucket_weight = worm_bucket_weight.getText().toString().equals("")? "0.0" : worm_bucket_weight.getText().toString();
                String water_weight = worm_water_weight.getText().toString().equals("")? "0.0" : worm_water_weight.getText().toString();
                String impurity_weight = worm_impurity_weight.getText().toString().equals("")? "0.0" : worm_impurity_weight.getText().toString();
                String feed_weight = worm_feed_weight.getText().toString().equals("")? "0.0" : worm_feed_weight.getText().toString();
                String cultivation_weight = worm_cultivation_weight.getText().toString().equals("")? "0.0" : worm_cultivation_weight.getText().toString();

                //四舍五入输入值再计算
                float new_net_weight = new BigDecimal((Float.parseFloat(income_weight) - Float.parseFloat(bucket_weight) - Float.parseFloat(impurity_weight)))
                        .setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
                worm_income_netweight.setText(new_net_weight+"");

                float new_throw_weight = new BigDecimal((Float.parseFloat(income_weight)
                        - Float.parseFloat(bucket_weight)
                        - Float.parseFloat(water_weight)
                        - Float.parseFloat(impurity_weight)
                        - Float.parseFloat(feed_weight)
                        - Float.parseFloat(cultivation_weight)))
                        .setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
                worm_throw_weight.setText(new_throw_weight+"");
            }
        };



        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/kitchenwaste/income/getlast" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Log.d("jy",response.toString());
                            JSONObject data;
                            if(jsonObject.get("data")!=null && !jsonObject.get("data").toString().equals("null")) {
                                data = jsonObject.getJSONObject("data");
                                if (!data.isNull("id")) {
                                    worm_incoming_incomeDate.setText(data.getString("incomeDate"));
                                    worm_income_weight.setText(data.getString("incomeWeight"));
                                    worm_bucket_weight.setText(data.getString("incomeNetweight"));
                                    worm_water_weight.setText(data.getString("bucketWeight"));
                                    worm_impurity_weight.setText(data.getString("waterWeight"));
                                    worm_income_netweight.setText(data.getString("impurityWeight"));
                                    worm_feed_weight.setText(data.getString("feedWeight"));
                                    worm_cultivation_weight.setText(data.getString("cultivationWeight"));
                                    worm_throw_weight.setText(data.getString("throwWeight"));
                                    remark.setText(data.getString("remark"));
                                    Toast.makeText(WormIncoming.this,
                                            "今日已填写此表", Toast.LENGTH_SHORT).show();
                                }
                            } else {
//                                worm_income_weight.setText("0");
//                                worm_bucket_weight.setText("0");
//                                worm_water_weight.setText("0");
//                                worm_impurity_weight.setText("0");
//                                worm_income_netweight.setText("0");
//                                worm_feed_weight.setText("0");
//                                worm_cultivation_weight.setText("0");
//                                worm_throw_weight.setText("0");
                            }
                            worm_income_weight.addTextChangedListener(weightChange_watcher);
                            worm_bucket_weight.addTextChangedListener(weightChange_watcher);
                            worm_water_weight.addTextChangedListener(weightChange_watcher);
                            worm_impurity_weight.addTextChangedListener(weightChange_watcher);
                            worm_feed_weight.addTextChangedListener(weightChange_watcher);
                            worm_cultivation_weight.addTextChangedListener(weightChange_watcher);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(WormIncoming.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    /**
     * 称重接口
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
            case "worm_income_weight_btn":
                worm_income_weight.setText(weight);
                break;
            case "worm_bucket_weight_btn":
                worm_bucket_weight.setText(weight);
                break;
            case "worm_water_weight_btn":
                worm_water_weight.setText(weight);
                break;
            case "worm_impurity_weight_btn":
                worm_impurity_weight.setText(weight);
                break;
            case "worm_income_netweight_btn":
                worm_income_netweight.setText(weight);
                break;
            case "worm_feed_weight_btn":
                worm_feed_weight.setText(weight);
                break;
            case "worm_cultivation_weight_btn":
                worm_cultivation_weight.setText(weight);
                break;
            case "worm_throw_weight_btn":
                worm_throw_weight.setText(weight);
                break;
        }
    }
    public void goWeight(View view) {
        switch (view.getId()) {
            case R.id.worm_income_weight_btn:
                activeButton = "worm_income_weight_btn";
                break;
            case R.id.worm_bucket_weight_btn:
                activeButton = "worm_bucket_weight_btn";
                break;
            case R.id.worm_water_weight_btn:
                activeButton = "worm_water_weight_btn";
                break;
            case R.id.worm_impurity_weight_btn:
                activeButton = "worm_impurity_weight_btn";
                break;
//            case R.id.worm_income_netweight_btn:
//                activeButton = "worm_income_netweight_btn";
//                break;
            case R.id.worm_feed_weight_btn:
                activeButton = "worm_feed_weight_btn";
                break;
            case R.id.worm_cultivation_weight_btn:
                activeButton = "worm_cultivation_weight_btn";
                break;
//            case R.id.worm_throw_weight_btn:
//                activeButton = "worm_throw_weight_btn";
//                break;
            default:
                break;
        }
        Intent intent = new Intent(WormIncoming.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }
    public void save(View view) {
        if (worm_income_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写来料重", Toast.LENGTH_SHORT).show();
            return;
        }
        if (worm_income_netweight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写来料净重", Toast.LENGTH_SHORT).show();
            return;
        }
        if (worm_bucket_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写桶重", Toast.LENGTH_SHORT).show();
            return;
        }
        if (worm_water_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写水重", Toast.LENGTH_SHORT).show();
            return;
        }if (worm_impurity_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写杂质重", Toast.LENGTH_SHORT).show();
            return;
        }if (worm_feed_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写进料重", Toast.LENGTH_SHORT).show();
            return;
        }if (worm_cultivation_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写培育重", Toast.LENGTH_SHORT).show();
            return;
        }if (worm_throw_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写丢弃重", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
            .setTitle("确定保存吗？")
            .setCancelable(false)
            .setNegativeButton("取消", ((dialog, which) ->
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
            .setPositiveButton("确定", (dialog, which) -> {

                //提交请求
                RequestQueue queue = Volley.newRequestQueue(this);
                String url = Config.url + "/kitchenwaste/income/add";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.d("jy", response);
                            if (response.toString().equals("true"))
                                Toast.makeText(WormIncoming.this,
                                        "保存成功", Toast.LENGTH_SHORT).show();
                            else
                                Toast.makeText(WormIncoming.this,
                                        "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(WormIncoming.this,
                                "保存失败" + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> map=new HashMap<>();
                        map.put("incomeDate", simpleDateFormat.format(incomingDate));
                        map.put("incomeWeight", worm_income_weight.getText().toString());
                        map.put("incomeNetweight",worm_income_netweight.getText().toString());
                        map.put("bucketWeight", worm_bucket_weight.getText().toString());
                        map.put("waterWeight", worm_water_weight.getText().toString());
                        map.put("impurityWeight", worm_impurity_weight.getText().toString());
                        map.put("feedWeight", worm_feed_weight.getText().toString());
                        map.put("cultivationWeight", worm_cultivation_weight.getText().toString());
                        map.put("throwWeight", worm_throw_weight.getText().toString());
                        map.put("remark", ((TextView) findViewById(R.id.worm_incoming_remark)).getText().toString());
                        map.put("recorder",name);
                        map.put("factory",factory);
                        return map;
                    }
                };
                stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue.add(stringRequest);
            })
            .show();
    }
}
